<script lang="ts" setup>
import { ElMessage, ElMessageBox, ElTree } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import { getDeptTree } from "@/api/system/dept";
import { getList, getDeptListApi } from "@/api/system/user";
defineOptions({
  name: "ShareDialogNew",
});

onMounted(() => {
  //获取树
  fetchDeptTree();
  // //获取成员
  getUserList();
});

// 弹窗展示与隐藏
const props = defineProps({
  visible: Boolean,
});
const emit = defineEmits<Emit>();
interface Emit {
  (e: "handleShareKg", userIdList: number[]): void;
  (e: "handleShareClose", visible: boolean): void;
}

/**
 * tab相关
 */
const activeName = ref("dept");
const handleTabChange = () => {
  shareList.value = [];
  checkUserList.value = [];
  deptData.value = [];
  nextTick(() => {
    treeRef.value.setCheckedNodes([]);
  });
};

// 左侧树形机构数据,部门相关
interface Tree {
  [key: string]: any;
}
const treeRef = ref<InstanceType<typeof ElTree>>();
const treeData = ref<Tree>();
const defaultprops = {
  label: "title",
  children: "children",
};
const fetchDeptTree = async () => {
  try {
    const { data } = await getDeptTree();
    treeData.value = data;
  } catch (error) {
    ElMessage.error(error);
  }
};
const deptData = ref([]);

const handleCheckChange = (checkedNodes, checkedKeys) => {
  deptData.value = checkedKeys.checkedNodes.filter((item) => {
    return !item.hasChildren;
  });
};
// const handleCheckChange = () => {
//   //判断，如果父级全选，只展示父级
//   deptData.value = getSimpleCheckedNodes(treeRef.value);
// };
const getSimpleCheckedNodes = (store) => {
  const checkedNodes = [];
  const traverse = function (node) {
    const childNodes = node.root ? node.root.childNodes : node.childNodes;
    childNodes.forEach((child) => {
      if (child.checked) {
        checkedNodes.push(child.data);
      }

      if (child.indeterminate) {
        traverse(child);
      }
    });
  };
  traverse(store);
  return checkedNodes;
};
const shareList = ref([]);
const handleTransferAll = () => {
  if (!deptData.value.length && !checkUserList.value.length) {
    ElMessage.warning("请至少构选一个");
    return;
  }
  if (activeName.value === "dept") {
    getDeptList();
  } else if (activeName.value === "user") {
    shareList.value = checkUserList.value;
  }
};
const getDeptList = async () => {
  let ids = deptData.value.map((item) => item.id);
  const { data } = await getDeptListApi({ inDeptId: ids });
  shareList.value = data;
};
const handleDelShare = (index) => {
  shareList.value.splice(index, 1);
};
const handleDelAll = () => {
  ElMessageBox.confirm("请确认是否全部删除吗？", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    shareList.value = [];
    ElMessage({
      type: "success",
      message: "删除成功",
    });
  });
};

//搜索相关
const deptFilterText = ref("");
const filterNode = (value: string, data: Tree) => {
  if (!value) return true;
  return data.title.includes(value);
};
const handleFilterTree = () => {
  treeRef.value!.filter(deptFilterText.value);
};
const loading = ref(false);
const noMore = computed(() => {
  return userPage.value * userSize.value >= userTotal.value;
});
const scrollDisable = computed(() => loading.value || noMore.value);
const userFilter = ref("");
const handleFilterUser = () => {
  userPage.value = 0;
  userList.value = [];
  getUserList();
};
/**
 * 成员相关
 */
const userList = ref([]);
const checkUserList = ref([]);
const userPage = ref(0);
const userSize = ref(9);
const userTotal = ref(0);
const getUserList = async () => {
  loading.value = true;
  userPage.value += 1;
  try {
    let { code, data } = await getList(userPage.value, userSize.value, {
      realName: userFilter.value,
    });
    if (code === 200) {
      userList.value = userList.value.concat(data.records);
      loading.value = false;
      userTotal.value = data.total;
    } else {
      loading.value = false;
    }
  } catch {
    loading.value = false;
  }
};
/**
 * 分享功能
 *
 */
const handleShareKg = () => {
  if (!shareList.value.length) {
    ElMessage.warning("请至少选择一个共享成员");
    return;
  }
  const userIdList = shareList.value.map((item) => item.id);
  emit("handleShareKg", userIdList);
};
const handleShareClose = () => {
  emit("handleShareClose", false);
};
</script>

<template>
  <el-dialog
    :model-value="props.visible"
    title="分享"
    width="696"
    @close="handleShareClose"
  >
    <el-row>
      <el-col :span="10" class="share-left">
        <el-tabs v-model="activeName" type="card" @tab-change="handleTabChange">
          <el-tab-pane label="部门" name="dept">
            <div class="dep-card">
              <el-input
                placeholder="搜索业务分类"
                v-model="deptFilterText"
                clearable
                @clear="handleFilterTree"
              >
                <template #suffix>
                  <el-icon
                    @click="handleFilterTree"
                    class="el-input__icon cursor-pointer"
                    ><search
                  /></el-icon>
                </template>
              </el-input>
              <el-tree
                :data="treeData"
                :props="defaultprops"
                show-checkbox
                node-key="id"
                ref="treeRef"
                :filter-node-method="filterNode"
                @check="handleCheckChange"
              />
            </div>
          </el-tab-pane>
          <el-tab-pane label="成员" name="user">
            <div class="dep-card user-card px-2 flex flex-col">
              <el-input
                placeholder="搜索业务分类"
                v-model="userFilter"
                clearable
                @clear="handleFilterUser"
              >
                <template #suffix>
                  <el-icon
                    @click="handleFilterUser"
                    class="el-input__icon cursor-pointer"
                    ><search
                  /></el-icon>
                </template>
              </el-input>
              <el-scrollbar
                class="infinite-list-wrapper flex-1"
                style="overflow-y: auto"
              >
                <ul
                  class="user-list"
                  v-infinite-scroll="getUserList"
                  :infinite-scroll-disabled="scrollDisable"
                  v-if="userList.length"
                >
                  <el-checkbox-group v-model="checkUserList">
                    <li
                      v-for="(user, index) in userList"
                      :key="index"
                      class="user-list-item"
                    >
                      <el-checkbox :label="user">
                        <span>{{ user.deptName }} - </span> {{ user.realName }}
                      </el-checkbox>
                    </li>
                  </el-checkbox-group>
                </ul>
                <empty-comp v-else></empty-comp>
                <p class="w-full h-5 leading-5 text-center" v-if="loading">
                  Loading...
                </p>
              </el-scrollbar>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-col>
      <el-col class="flex items-center" :span="2" :offset="1">
        <div
          class="share-circle flex justify-center items-center"
          :class="deptData.length || checkUserList.length ? 'active' : ''"
          @click="handleTransferAll"
        >
          <i class="iconfont icon_arrow_right"></i>
        </div>
      </el-col>
      <el-col :span="10" class="share-right flex flex-col">
        <div
          class="share-right-header flex justify-between items-center leading-10 px-2"
        >
          <div>共享成员（{{ shareList.length }}）</div>
          <el-button @click="handleDelAll" type="primary" size="small"
            >全部删除</el-button
          >
        </div>
        <ul class="share-right-list overflow-hidden px-2 flex-1">
          <el-scrollbar v-if="shareList.length">
            <li
              v-for="(member, index) in shareList"
              :key="member.id"
              class="share-right-item flex justify-between"
            >
              <div>
                {{ member.deptName }} <span v-if="member.deptName">-</span>
                {{ member.realName }}
              </div>
              <div
                @click="handleDelShare(index)"
                class="iconfont icon_delete_fill cursor-pointer"
              ></div>
            </li>
          </el-scrollbar>
          <empty-comp v-else></empty-comp>
        </ul>
      </el-col>
    </el-row>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleShareClose">取消</el-button>
        <el-button type="primary" @click="handleShareKg"> 分享 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.share-left {
  &::v-deep .el-tabs--card > .el-tabs__header {
    margin-bottom: 0;
    border-bottom: none;
  }

  .dep-card {
    width: 100%;
    height: 353px;
    padding: 0 8px;
    background: #fff;
    border: 1px solid #edeff4;
    border-radius: 0 4px 4px;

    .el-input {
      margin: 10px 0;

      &::v-deep .el-input__wrapper {
        border-radius: 20px;
      }
    }
  }

  .user-list-item {
    &::v-deep .el-checkbox {
      height: 34px;
      margin-left: 1px;
    }
  }
}

.share-circle {
  width: 40px;
  height: 40px;
  cursor: not-allowed;
  background: #f2f4f9;
  border-radius: 40px;
}

.share-circle.active {
  color: #fff;
  cursor: pointer;
  background: #2b1dff;
}

.share-right {
  height: 393px;
  background: #fff;
  border: 1px solid #edeff4;
  border-radius: 4px 4px 0 0;

  .share-right-header {
    margin-bottom: 8px;
    border-bottom: 1px solid #edeff4;
  }

  .share-right-item {
    padding: 0 16px;
    line-height: 32px;

    &:hover {
      color: #2b1dff;
      background-color: #f7f8fa;
    }
  }
}
</style>
